//
//  CleanOrderController.m
//  carowner
//
//  Created by apple on 2019/5/23.
//  Copyright © 2019 ggj. All rights reserved.
//

#import "CleanOrderController.h"
#import "WeekCell.h"
#import "OrderTimeCell.h"
#import "YLButton.h"
#import "WeekEntity.h"
#import "OrderParams.h"
#import "OrderWeekList.h"
#import "OrderTimeList.h"
#import "CarListEntity.h"
#import "AddConventionParams.h"
#import "CarInfoDetails.h"
#import "ComEntity.h"
#import "WashPriceController.h"

@interface CleanOrderController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic,strong)UITableView * weekView;
@property(nonatomic,strong)UIButton * cleanPrice;
@property(nonatomic,strong)UIScrollView * timeScroller;
@property(nonatomic,strong)UICollectionView * amView;
@property(nonatomic,strong)UICollectionView * pmView;
@property(nonatomic,strong)YLButton * amTip;
@property(nonatomic,strong)YLButton * pmTip;
@property(nonatomic,strong)UIButton * btnOrder;
@property(nonatomic,strong)NSMutableArray<OrderWeekList *> * dateArray;

@property(nonatomic,strong)NSMutableArray<OrderTimeList *> * amTimeList;
@property(nonatomic,strong)NSMutableArray<OrderTimeList *> * pmTimeList;

@property(nonatomic,strong)NSArray * carArray;
@property(nonatomic,strong)OrderTimeList * selectTime;

//if (type.equals("1")) {
//    tv_more.setText("洗车价格列表");
//    titleView.setTitle("洗车预约");
//    conventionTypeId = "2c9087286468230801646e9b1e180086";
//} else if (type.equals("2")) {
//    tv_more.setText("保养项目列表");
//    titleView.setTitle("保养预约");
//    conventionTypeId = "297ebd7262b8b9c00162b8bb29bf0003";
//} else if (type.equals("3")) {
//    tv_more.setText("美容项目列表");
//    titleView.setTitle("美容预约");
//    conventionTypeId = "2c9087286468230801646e9b1e180085";
//}
@property(nonatomic,strong)NSString * typeCode;

@end

@implementation CleanOrderController

- (void)viewDidLoad {
    [super viewDidLoad];
    if((int)_type == 1){
        self.title = @"洗车预约";
        _typeCode = @"2c9087286468230801646e9b1e180086";
    }

    _dateArray = [[NSMutableArray alloc] init];
    _amTimeList = [[NSMutableArray alloc] init];
    _pmTimeList = [[NSMutableArray alloc] init];
//    [self initDate];
    
    _weekView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0,0) style:UITableViewStylePlain];
    _weekView.delegate = self;
    _weekView.dataSource = self;
    _weekView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_weekView registerClass:[WeekCell class] forCellReuseIdentifier:@"weekId"];
    _weekView.backgroundColor = light_color;
    
    _cleanPrice = [UIButton buttonWithType:UIButtonTypeCustom];
    [_cleanPrice setTitle:@"洗车价格列表>>" forState:UIControlStateNormal];
    [_cleanPrice setTitleColor:color2 forState:UIControlStateNormal];
    [_cleanPrice setFont:textFont];
    [_cleanPrice addTarget:self action:@selector(lookPrice) forControlEvents:UIControlEventTouchUpInside];
    
    _amTip = [YLButton buttonWithType:UIButtonTypeCustom];
    [_amTip setFont:textFont];
    [_amTip setImage:[UIImage imageNamed:@"time"] forState:UIControlStateNormal];
    [_amTip setTitle:@"上午" forState:UIControlStateNormal];
    [_amTip setTitleColor:color2 forState:UIControlStateNormal];
    _amTip.imageRect = CGRectMake(10, 10, 20, 20);
    _amTip.titleRect = CGRectMake(35, 10, 30, 20);
    
    UICollectionViewFlowLayout * amLayout = [[UICollectionViewFlowLayout alloc]init];
    amLayout.minimumInteritemSpacing = 0;
    amLayout.minimumLineSpacing = 0;
    amLayout.minimumInteritemSpacing = 0;
    amLayout.minimumLineSpacing = 0;
    
    _amView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:amLayout];
    _amView.delegate = self;
    _amView.dataSource = self;
    _amView.contentInset = UIEdgeInsetsMake(5,5,5,5);
    _amView.backgroundColor = [UIColor clearColor];
    [_amView registerClass:[OrderTimeCell class] forCellWithReuseIdentifier:@"amId"];
    
    UICollectionViewFlowLayout * pmLayout = [[UICollectionViewFlowLayout alloc]init];
    pmLayout.minimumInteritemSpacing = 0;
    pmLayout.minimumLineSpacing = 0;
    pmLayout.minimumInteritemSpacing = 0;
    pmLayout.minimumLineSpacing = 0;
    
    _pmView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:pmLayout];

    _pmView.delegate = self;
    _pmView.dataSource = self;
    _pmView.contentInset = UIEdgeInsetsMake(5,5,5,5);
    _pmView.backgroundColor = [UIColor clearColor];
    [_pmView registerClass:[OrderTimeCell class] forCellWithReuseIdentifier:@"pmId"];
    
    
    _pmTip = [YLButton buttonWithType:UIButtonTypeCustom];
    [_pmTip setFont:textFont];
    [_pmTip setImage:[UIImage imageNamed:@"time"] forState:UIControlStateNormal];
    [_pmTip setTitle:@"下午" forState:UIControlStateNormal];
    [_pmTip setTitleColor:color2 forState:UIControlStateNormal];
    _pmTip.imageRect = CGRectMake(10, 10, 20, 20);
    _pmTip.titleRect = CGRectMake(35, 10, 30, 20);
    
    _btnOrder = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnOrder.backgroundColor = color2;
    [_btnOrder setTitle:@"立即预约" forState:UIControlStateNormal];
    [_btnOrder setFont:textFont];
    [_btnOrder addTarget:self action:@selector(doOrder) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_weekView];
    [self.view addSubview:_cleanPrice];
    [self.view addSubview:_amTip];
    [self.view addSubview:_amView];
    [self.view addSubview:_pmTip];
    [self.view addSubview:_pmView];
    [self.view addSubview:_btnOrder];
    
    [_weekView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(getRectNavAndStatusHight);
        make.left.equalTo(self.view);
        make.width.mas_equalTo(100);
        make.bottom.equalTo(self.view).offset(-kSafeArea_Bottom-60);
    }];
    
    [_cleanPrice mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-10);
        make.top.equalTo(self.view).offset(getRectNavAndStatusHight+10);
        make.height.mas_equalTo(20);
    }];
    
    [_amTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_cleanPrice.mas_bottom);
        make.left.equalTo(_weekView.mas_right).offset(15);
        make.size.mas_equalTo(CGSizeMake(65, 20));
    }];
    
    [_amView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_amTip.mas_bottom).offset(15);
        make.left.equalTo(_weekView.mas_right);
        make.right.equalTo(self.view);
        make.height.mas_equalTo((kScreen_Height - getRectNavAndStatusHight -250-kSafeArea_Bottom)/2);
    }];
    
    
    [_pmTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_amView.mas_bottom);
        make.left.equalTo(_weekView.mas_right).offset(15);
        make.size.mas_equalTo(CGSizeMake(65, 20));
    }];
    
    [_pmView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_pmTip.mas_bottom).offset(15);
        make.left.equalTo(_weekView.mas_right);
        make.right.equalTo(self.view);
            make.bottom.equalTo(self.view).offset(-kSafeArea_Bottom-60);
    }];
    
    [_btnOrder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(40);
        make.bottom.equalTo(self.view).offset(-kSafeArea_Bottom-10);
    }];
    // Do any additional setup after loading the view.
    
    OrderParams * params = [[OrderParams alloc] init];
    params.type = [NSString stringWithFormat:@"%d",(int)_type];
    params.orgid = _shopId;
    [[ApiManager sharedManager] getShopOrderTime:[params mj_JSONObject]andBlock:^(id data, NSError *error) {
        id resultData = [data valueForKeyPath:ResultList];
        NSArray * dataArray = [OrderWeekList mj_objectArrayWithKeyValuesArray:resultData];
        [_dateArray addObjectsFromArray:dataArray];
        [_dateArray objectAtIndex:0].check = YES;
        NSArray<OrderTimeList *> * timeList = [_dateArray objectAtIndex:0].list;
        
        for(OrderTimeList * entity in timeList){
            if([entity.start_time doubleValue] <12){
                [_amTimeList addObject:entity];
            }else{
                [_pmTimeList addObject:entity];
            }
        }
        [_weekView reloadData];
        [_amView reloadData];
        [_pmView reloadData];
    }];
    NSDictionary * dct = [[NSDictionary alloc] initWithObjectsAndKeys:TEST_CUSTOMER_ID,@"id", nil];
    [[ApiManager sharedManager] getCarList: dct andBlock:^(id data, NSError *error) {
        id resultData = [data valueForKeyPath:ResultList];
        _carArray = [CarListEntity mj_objectArrayWithKeyValuesArray:resultData];
    }];
}

-(void)lookPrice{
    WashPriceController * controller = [[WashPriceController alloc] init];
    controller.orgID = _shopId;
    [self.navigationController pushViewController:controller animated:YES];
}

//-(void)initDate{
//    _dateArray = [[NSMutableArray alloc] init];
//    for(int i = 0 ; i < 7 ; i++){
//        long time = [[NSDate date] timeIntervalSince1970];
//        NSString * date = [NSString getTimeFromTimestamp:time+24*60*60*i];
//        NSString * week = [NSString dateWeekWithDateString:[NSString stringWithFormat:@"%ld",time+24*60*60*i]];
//        NSString * newStr = [NSString stringWithFormat:@"%@\n%@",date,week];
//        WeekEntity * entity = [[WeekEntity alloc]init];
//        entity.str = newStr;
//        if(i == 0){
//            entity.check = YES;
//        }else{
//            entity.check = NO;
//        }
//        [_dateArray addObject:entity];
//    }
//
//}

/**
  提交预约单
 */
-(void)doOrder{
    if(_carArray == nil ||_carArray.count == 0){
        [NSObject showHudTipStr:@"请添加车辆!"];
    }
    [MyUtils showChooseCheckView:self.view withTitle:@"预约" withPropertyName:@"plateNumber" andData:_carArray withBlock:^(id entity) {
        CarListEntity * carEntity = entity;
        NSString * carNum = [carEntity.plateNumber stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];;
        NSDictionary * dct = [[NSDictionary alloc] initWithObjectsAndKeys:carNum,@"plateNumber", nil];
        [[ApiManager sharedManager] getInfoByPlateNumber:dct andBlock:^(id data, NSError *error) {
            id detailsData = [data valueForKeyPath:ReturnObject];
            CarInfoDetails * carDetails = [CarInfoDetails mj_objectWithKeyValues:detailsData];
            AddConventionParams * params = [[AddConventionParams alloc] init];
            params.customerId = TEST_CUSTOMER_ID;
            params.phone = carDetails.telephone;
            params.cardNumber = carDetails.plateNumber;
            params.name = carDetails.personName;
            params.type = [NSString stringWithFormat:@"%ld",(long)_type];
            params.conventionTime = [NSString stringWithFormat:@"%@ %@",_selectTime.dateTime,_selectTime.start_time];
            params.end_time = [NSString stringWithFormat:@"%@ %@",_selectTime.dateTime,_selectTime.end_time];
            params.conventionTypeId = _typeCode;
            params.org_time_id = _selectTime.idField;
            NSMutableArray<ComEntity *> * comArray = [[NSMutableArray alloc] init];
            ComEntity * com = [[ComEntity alloc] init];
            com.companyId = _comID;
            [comArray addObject:com];
            params.companyList = comArray;
            [[ApiManager sharedManager] addConvention:[params mj_JSONObject] andBlock:^(id data, NSError *error) {
                [NSObject showHudTipStr:@"预约成功!"];
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dateArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WeekCell * cell = [tableView dequeueReusableCellWithIdentifier:@"weekId"];
    
    OrderWeekList * entity = [_dateArray objectAtIndex:indexPath.row];
    cell.dateTip.text = [NSString stringWithFormat:@"%@\n%@",entity.dateTime,entity.weekName];
    if(indexPath.row == 0){
        cell.topTip.hidden = NO;
    }
    if([_dateArray objectAtIndex:indexPath.row].check){
        cell.dateTip.backgroundColor = check_color;
    }else{
        cell.dateTip.backgroundColor = light_color;
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(collectionView == _amView){
        return _amTimeList.count;
    }else if(collectionView == _pmView){
        return _pmTimeList.count;
    }else{
        return 0;
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if(collectionView == _amView){
        OrderTimeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"amId" forIndexPath:indexPath];
        OrderTimeList * entity = [_amTimeList objectAtIndex:indexPath.row];
        cell.tvTime.text = [NSString stringWithFormat:@"%@-%@",entity.start_time,entity.end_time];
        cell.tvNum.text = [NSString stringWithFormat:@"%d/%d",(int)entity.nowNum,(int)entity.max_num];
        
        long time = [[NSDate date] timeIntervalSince1970];
        NSString * itemAll = [[NSString stringWithFormat:@"%@%@",entity.dateTime,entity.end_time] stringByReplacingOccurrencesOfString:@"-" withString:@""];
        
        double itemVal= [[itemAll stringByReplacingOccurrencesOfString:@":" withString:@"."] doubleValue];
        
        NSString * nowAll = [[[[NSString getYMDHM:time] stringByReplacingOccurrencesOfString:@":" withString:@"."] stringByReplacingOccurrencesOfString:@" " withString:@""] stringByReplacingOccurrencesOfString:@"-" withString:@""];
        
        double nowVal = [nowAll doubleValue];
        //state 1超时 2预约已满 3可预约 4选中
        if(itemVal < nowVal){
            cell.backgroundColor = color1;
            entity.state = 1;
        }else{
            if(entity.nowNum == entity.max_num){
                cell.backgroundColor = color2;
                entity.state = 2;
            }else if(entity.nowNum < entity.max_num){
                if(entity.check){
                    cell.backgroundColor = color4;
                    entity.state = 4;
                }else{
                    cell.backgroundColor = color3;
                    entity.state = 3;
                }
            }
        }

        return cell;
    }else if(collectionView == _pmView){
        OrderTimeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pmId" forIndexPath:indexPath];
        OrderTimeList * entity = [_pmTimeList objectAtIndex:indexPath.row];
        cell.tvTime.text = [NSString stringWithFormat:@"%@-%@",entity.start_time,entity.end_time];
        cell.tvNum.text = [NSString stringWithFormat:@"%d/%d",(int)entity.nowNum,(int)entity.max_num];
        
        long time = [[NSDate date] timeIntervalSince1970];
        
        NSString * itemAll = [[NSString stringWithFormat:@"%@%@",entity.dateTime,entity.end_time] stringByReplacingOccurrencesOfString:@"-" withString:@""];
        
        double itemVal= [[itemAll stringByReplacingOccurrencesOfString:@":" withString:@"."] doubleValue];
        
        NSString * nowAll = [[[[NSString getYMDHM:time] stringByReplacingOccurrencesOfString:@":" withString:@"."] stringByReplacingOccurrencesOfString:@" " withString:@""] stringByReplacingOccurrencesOfString:@"-" withString:@""];
        
        double nowVal = [nowAll doubleValue];

        //state 1超时 2预约已满 3可预约 4选中
        if(itemVal < nowVal){
            cell.backgroundColor = color1;
            entity.state = 1;
        }else{
            if(entity.nowNum == entity.max_num){
                cell.backgroundColor = color2;
                entity.state = 2;
            }else if(entity.nowNum < entity.max_num){
                if(entity.check){
                    cell.backgroundColor = color4;
                    entity.state = 4;
                }else{
                    cell.backgroundColor = color3;
                    entity.state = 3;
                }
            }
        }
        return cell;
    }else{
        return nil;
    }
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((kScreen_Width - 120)/2, 88);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [_amTimeList removeAllObjects];
    [_pmTimeList removeAllObjects];
    
    for(int i = 0 ; i < _dateArray.count ;i++){
        if(indexPath.row == i){
            [_dateArray objectAtIndex:i].check = YES;
        }else{
           [_dateArray objectAtIndex:i].check = NO;
        }
    }
    
    NSArray<OrderTimeList *> * timeList = [_dateArray objectAtIndex:indexPath.row].list;
    
    for(OrderTimeList * entity in timeList){
        if([entity.start_time doubleValue] <12){
            [_amTimeList addObject:entity];
        }else{
            [_pmTimeList addObject:entity];
        }
    }
    
    [_weekView reloadData];
    [_amView reloadData];
    [_pmView reloadData];
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
 
    if(collectionView == _amView){
        OrderTimeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"amId" forIndexPath:indexPath];
        OrderTimeList * entity = [_amTimeList objectAtIndex:indexPath.row];
        if(entity.state == 1 || entity.state == 2){
            [NSObject showHudTipStr:@"当前时间段不可选择!"];
            return;
        }else if(entity.state == 3){
            entity.state = 4;
            entity.check = YES;
            _selectTime = entity;
            for(OrderTimeList * amEntity  in _amTimeList){
                if(entity!=amEntity){
                    amEntity.check = NO;
                }
            }
            for(OrderTimeList * pmEntity  in _pmTimeList){
                pmEntity.check = NO;
            }
        }else if(entity.state == 4){
            entity.state = 3;
            entity.check = NO;
            _selectTime = nil;
        }
        [_amView reloadData];
        [_pmView reloadData];
        
    }else if(collectionView == _pmView){
        OrderTimeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pmId" forIndexPath:indexPath];
        OrderTimeList * entity = [_pmTimeList objectAtIndex:indexPath.row];
        if(entity.state == 1 || entity.state == 2){
            [NSObject showHudTipStr:@"当前时间段不可选择!"];
            return;
        }else if(entity.state == 3){
            entity.state = 4;
            entity.check = YES;
             _selectTime = entity;
            for(OrderTimeList * amEntity  in _amTimeList){
                amEntity.check = NO;
            }
            for(OrderTimeList * pmEntity  in _pmTimeList){
                if(entity!=pmEntity){
                    pmEntity.check = NO;
                }
            }
        }else if(entity.state == 4){
            entity.state = 3;
            entity.check = NO;
            _selectTime = nil;
        }
        [_amView reloadData];
        [_pmView reloadData];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
